package com.wyw.learning.thread.future;

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 演示批量提交任务时，用List来批量接收结果
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
public class MultiFutures {
    public static void main(String[] args) throws Exception {
        //20个线程同时打印出来，看起来是在机器上同时执行的，是因为在调用sleep期间不再占用CPU的资源，所以就算是4核的机器每次只能执行4个线程，但是因为释放cpu资源的时间太快，另外四个马上又能拿到cpu资源，所以看起来是同时的
        ExecutorService service = Executors.newFixedThreadPool(20);//现象可以通过修改线程数目观察
        ArrayList<Future> futures = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            Future<Integer> future = service.submit(new CallableTask());
            futures.add(future);
        }
        Thread.sleep(5000);

        for(int i = 0; i<20;i++) { // submit的顺序和future.get的顺序不一致会死等
            Future<Integer> integerFuture = futures.get(i);
            Integer integer = integerFuture.get();
            System.out.println(integer);

        }
        service.shutdown();

    }

    static class CallableTask implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            Thread.sleep(3000);
            return new Random().nextInt();
        }
    }
}
